package com.hexinfo.dmpro.monitor.service;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hexinfo.dmpro.common.utils.StringUtils;
import com.hexinfo.dmpro.monitor.dao.ClusterHostDao;
import com.hexinfo.dmpro.monitor.model.ClusterHostModel;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.base.MonitorRsp;
import com.hexinfo.dmpro.monitor.service.serviceparam.CmTargetParamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * @author peng
 * @date 2022/2/15 15:18
 */
@Service
@Slf4j
public class ClusterHostService {

    private int SUCESS_CODE = 200;

    @Autowired
    private CmApiService cmApiService;
    @Autowired
    private ClusterHostDao clusterHostDao;
    @Autowired
    private CmTargetParamService cmTargetParamService;

    private String apiUrl = "/hosts?view=FULL";

    @Value("${warn.cmHostsHealthSummary}")
    private String cmHostsHealthSummary;

    public List<ClusterHostModel> getHostInfo(MonitorReq req, boolean flag) {
        Map<String, Object> map = new HashMap();
        List<ClusterHostModel> items = new ArrayList<>();
        String warnAlert = "";

        JSONObject jsonObject = JSONObject.parseObject(req.getOtherParam());
        //配置cm Api的 url
        String url = jsonObject.get("cmApi").toString();
        req.setUrl(url+apiUrl);
        String user = jsonObject.get("user").toString();
        String password = jsonObject.get("password").toString();

        Map header = new HashMap<>();
        try {
            header.put("Authorization", "Basic " + Base64.getEncoder().encodeToString((user + ":" + password).getBytes("utf-8")));
            req.setHeader(header);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        MonitorRsp rsp = cmApiService.execute(req);
        if (SUCESS_CODE == rsp.getCode()) {
            //删除某个集群数据 再新增集群数据
            String body = rsp.getBody();
            JSONObject obj = JSONObject.parseObject(body);
            JSONArray jsonArray = obj.getJSONArray("items");
            for (int i = 0; i < jsonArray.size(); i++) {
                ClusterHostModel clusterHostModel = new ClusterHostModel();
                JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                JSONObject clusterRef = jsonObject1.getJSONObject("clusterRef");
                if(clusterRef !=null && StringUtils.isNotBlank(clusterRef.getString("displayName"))){
                    clusterHostModel.setHostName(jsonObject1.getString("hostname"));
                    clusterHostModel.setIp(jsonObject1.getString("ipAddress"));
                    clusterHostModel.setHostId(jsonObject1.getString("hostId"));
                    clusterHostModel.setHealthSummary(jsonObject1.getString("healthSummary"));
                    clusterHostModel.setDisplayName(clusterRef.getString("displayName"));
                    clusterHostModel.setClusterFlag(clusterRef.getString("clusterName"));
                    clusterHostModel.setClusterName(clusterRef.getString("clusterName"));
                    items.add(clusterHostModel);
                    if ("BAD".equals(jsonObject1.getString("healthSummary"))){
                        warnAlert = warnAlert + jsonObject1.getString("ipAddress") + " 主机状态: 异常"+"\n";
                    }
                }
            }
            try {
                if (StrUtil.isNotBlank(warnAlert)) {
                    String warnStr = "CM主机监控：\n" + "【" + req.getCmName() + "】" + "\n" + warnAlert;
                    //发送日常巡检，钉钉
                    cmTargetParamService.warnWxDingDingAndLog(req.getCmFlag(), req.getCmName(), req.getClusterFlag(), req.getClusterName(), "集群主机", warnStr, cmHostsHealthSummary);
                }
            }catch (Exception e){
                log.error("主机状态监控发送告警异常："+e);
            }
            map.put("list", items);
            map.put("req", req);
            if(flag){
                clusterHostDao.delClusterInfo(req);
                clusterHostDao.insertClusterInfo(map);
            }
        }
        return items;
    }


}
